// 新增：格式化描述中的URL为链接
function formatDescWithLinks(desc) {
  if (!desc) return '';
  
  // 转义HTML标签
  let formattedDesc = desc.replace(/</g, '&lt;').replace(/>/g, '&gt;');
  
  // 使用更简单可靠的方法：先识别所有位置，然后从后向前替换
  // 这样可以避免替换过程中位置变化导致的问题
  
  // 先处理Markdown格式的链接 [文本](URL)
  let matches = [];
  let regex = /\[([^\]]+)\]\(([^)]+)\)/g;
  let match;
  
  // 收集所有匹配
  while ((match = regex.exec(formattedDesc)) !== null) {
    matches.push({
      fullMatch: match[0],
      text: match[1],
      url: match[2],
      index: match.index
    });
  }
  
  // 从后向前替换，避免位置变化
  for (let i = matches.length - 1; i >= 0; i--) {
    const m = matches[i];
    const replacement = `<a href="${m.url}" target="_blank" style="color:#1677ff;text-decoration:underline;">${m.text}</a>`;
    formattedDesc = 
      formattedDesc.substring(0, m.index) + 
      replacement + 
      formattedDesc.substring(m.index + m.fullMatch.length);
  }
  
  // 再处理普通URL，这次也是收集后从后向前替换
  matches = [];
  regex = /(https?:\/\/[^\s]+)/g;
  
  while ((match = regex.exec(formattedDesc)) !== null) {
    // 简单检查是否在<a>标签内
    const beforeMatch = formattedDesc.substring(0, match.index);
    const lastOpenTag = beforeMatch.lastIndexOf('<a');
    const lastCloseTag = beforeMatch.lastIndexOf('</a>');
    
    // 如果最后一个打开标签在最后一个关闭标签之后，那么我们在标签内
    if (lastOpenTag > lastCloseTag && lastOpenTag !== -1) {
      continue; // 跳过这个匹配
    }
    
    matches.push({
      fullMatch: match[0],
      index: match.index
    });
  }
  
  // 从后向前替换
  for (let i = matches.length - 1; i >= 0; i--) {
    const m = matches[i];
    const replacement = `<a href="${m.fullMatch}" target="_blank" style="color:#1677ff;text-decoration:underline;">${m.fullMatch}</a>`;
    formattedDesc = 
      formattedDesc.substring(0, m.index) + 
      replacement + 
      formattedDesc.substring(m.index + m.fullMatch.length);
  }
  
  // 处理换行
  formattedDesc = formattedDesc.replace(/\n/g, '<br>');
  
  return formattedDesc;
}

function formatDateTime(dt) {
  if (!dt) return '';
  const d = new Date(dt);
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
}
function formatDuration(start, end, timerSegments, showSeconds) {
  // 新增：支持分段计时
  if (timerSegments && Array.isArray(timerSegments) && timerSegments.length > 0) {
    let totalMs = 0;
    timerSegments.forEach(seg => {
      if (seg.start && seg.end) {
        totalMs += new Date(seg.end) - new Date(seg.start);
      } else if (seg.start && !seg.end) {
        totalMs += new Date() - new Date(seg.start);
      }
    });
    let min = Math.floor(totalMs / 60000);
    let sec = Math.floor((totalMs % 60000) / 1000);
    if (min < 1) {
      return `${sec}s`;
    }
    if (min < 60) {
      // 无论showSeconds如何，只要有秒都显示
      return sec > 0 ? `${min}min/${sec}s` : `${min}min`;
    } else {
      const h = Math.floor(min / 60);
      const m = min % 60;
      if (sec > 0) {
        return m === 0 ? `${h}h/${sec}s` : `${h}h/${m}min/${sec}s`;
      }
      if (m === 0) return `${h}h`;
      return `${h}h/${m}min`;
    }
  }
  // 兼容老数据
  if (!start || !end) return '';
  const ms = new Date(end) - new Date(start);
  if (ms < 0) return '';
  let min = Math.floor(ms / 60000);
  let sec = Math.floor((ms % 60000) / 1000);
  if (min < 1) {
    return `${sec}s`;
  }
  if (min < 60) {
    return sec > 0 ? `${min}min/${sec}s` : `${min}min`;
  } else {
    const h = Math.floor(min / 60);
    const m = min % 60;
    if (sec > 0) {
      return m === 0 ? `${h}h/${sec}s` : `${h}h/${m}min/${sec}s`;
    }
    if (m === 0) return `${h}h`;
    return `${h}h/${m}min`;
  }
}

function isSameDay(dateStr, y, m, d) {
  if (!dateStr) return false;
  const dt = new Date(dateStr);
  return dt.getFullYear() === y && dt.getMonth() + 1 === m && dt.getDate() === d;
}

let allTasksCache = [];
let liveTimerInterval = null;

function getFilterDateRange() {
  const start = document.getElementById('doneDateStart').value;
  const end = document.getElementById('doneDateEnd').value;
  return { start, end };
}

function refreshAllLiveTimers() {
  const allLiveTimers = document.querySelectorAll('.live-timer');
  allLiveTimers.forEach(span => {
    const createdAt = span.getAttribute('data-createdat');
    const task = allTasksCache.find(t => t.createdAt === createdAt && t.status === '进行中');
    if (task && task.timerSegments && task.timerSegments.length > 0 && !task.timerPaused) {
      span.textContent = formatDuration(null, null, task.timerSegments, true);
    } else if (task && task.timerSegments && task.timerSegments.length > 0 && task.timerPaused) {
      span.textContent = formatDuration(null, null, task.timerSegments, false);
    }
  });
}

function renderAllTasks(tasks, filterDateRange) {
  const list = document.getElementById('allTaskList');
  list.innerHTML = '';
  // 统计
  const inProgressCount = tasks.filter(t => t.status === '进行中').length;
  const pendingCount = tasks.filter(t => t.status === '待处理').length;
  const doneCount = tasks.filter(t => t.status === '已完成').length;
  document.getElementById('statsBar').innerHTML = `In Progress: <span style='color:#1677ff'>${inProgressCount}</span>  |  Pending: <span style='color:#faad14'>${pendingCount}</span>  |  Done: <span style='color:#52c41a'>${doneCount}</span>`;

  // 筛选
  let inProgress = tasks.filter(t => t.status === '进行中').sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  let pending = tasks.filter(t => t.status === '待处理').sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  let done = tasks.filter(t => t.status === '已完成');
  if (filterDateRange && (filterDateRange.start || filterDateRange.end)) {
    done = done.filter(t => {
      if (!t.completedAt) return false;
      const completed = new Date(t.completedAt).setHours(0,0,0,0);
      let inRange = true;
      if (filterDateRange.start) {
        const start = new Date(filterDateRange.start).setHours(0,0,0,0);
        inRange = inRange && completed >= start;
      }
      if (filterDateRange.end) {
        const end = new Date(filterDateRange.end).setHours(0,0,0,0);
        inRange = inRange && completed <= end;
      }
      return inRange;
    });
  }
  done = done.sort((a, b) => new Date(b.completedAt) - new Date(a.completedAt));

  if (inProgress.length > 0) {
    const inProgressTitle = document.createElement('li');
    inProgressTitle.textContent = 'In Progress';
    inProgressTitle.className = 'list-title in-progress-title';
    list.appendChild(inProgressTitle);
    inProgress.forEach((task, idx) => renderAllTaskItem(task));
  }
  if (pending.length > 0) {
    const pendingTitle = document.createElement('li');
    pendingTitle.textContent = 'Pending';
    pendingTitle.className = 'list-title pending-title';
    list.appendChild(pendingTitle);
    pending.forEach((task, idx) => renderAllTaskItem(task));
  }
  if (done.length > 0) {
    const doneTitle = document.createElement('li');
    doneTitle.textContent = 'Done';
    doneTitle.className = 'list-title done-title';
    list.appendChild(doneTitle);
    done.forEach((task, idx) => renderAllTaskItem(task));
  }
  if (inProgress.length === 0 && done.length === 0 && pending.length === 0) {
    const empty = document.createElement('li');
    empty.textContent = 'No tasks.';
    empty.className = 'list-title';
    list.appendChild(empty);
  }
  // 渲染后启动/重启全局定时器
  if (liveTimerInterval) clearInterval(liveTimerInterval);
  liveTimerInterval = setInterval(refreshAllLiveTimers, 1000);
}

function renderAllTaskItem(task) {
  let statusClass = 'task-status';
  if (task.status === '进行中') statusClass += ' in-progress';
  else if (task.status === '待处理') statusClass += ' pending';
  let statusText = task.status;
  if (task.status === '进行中') statusText = 'In Progress';
  else if (task.status === '已完成') statusText = 'Done';
  else if (task.status === '待处理') statusText = 'Pending';
  let durationStr = '';
  if (task.status === '已完成' && task.timerSegments && task.timerSegments.length > 0) {
    durationStr = `<span style='color:#faad14;font-size:12px;margin-left:8px;'>${formatDuration(null, null, task.timerSegments, false)}</span>`;
  } else if (task.status === '已完成' && task.createdAt && task.completedAt) {
    durationStr = `<span style='color:#faad14;font-size:12px;margin-left:8px;'>${formatDuration(task.createdAt, task.completedAt, null, false)}</span>`;
  } else if (task.status === '进行中' && task.timerSegments && task.timerSegments.length > 0) {
    durationStr = `<span style='color:#faad14;font-size:12px;margin-left:8px;' class='live-timer' data-createdat='${task.createdAt}'>${formatDuration(null, null, task.timerSegments, !task.timerPaused)}</span>`;
  }
  const li = document.createElement('li');
  li.className = task.status === '已完成' ? 'completed' : '';
  let btnGroup = `<button class=\"delete-btn\" data-createdat=\"${task.createdAt || ''}\" data-title=\"${task.title}\">Delete</button>`;
  if (task.status === '进行中') {
    // 新增：开始/暂停按钮
    let playPauseIcon = '';
    if (task.timerPaused) {
      playPauseIcon = `<svg class='play-pause-btn' data-createdat='${task.createdAt}' width='18' height='18' viewBox='0 0 24 24' style='vertical-align:middle;cursor:pointer;' title='继续'><polygon points='5,3 19,12 5,21' fill='#1677ff'/></svg>`;
    } else {
      playPauseIcon = `<svg class='play-pause-btn' data-createdat='${task.createdAt}' width='18' height='18' viewBox='0 0 24 24' style='vertical-align:middle;cursor:pointer;' title='暂停'><rect x='6' y='4' width='4' height='16' fill='#1677ff'/><rect x='14' y='4' width='4' height='16' fill='#1677ff'/></svg>`;
    }
    btnGroup = `${playPauseIcon} <button class=\"revert-btn\" data-createdat=\"${task.createdAt}\">Revert</button> <button class=\"done-btn\" data-createdat=\"${task.createdAt}\">Done</button> ` + btnGroup;
  } else if (task.status === '待处理') {
    btnGroup = `<button class=\"start-btn\" data-title=\"${task.title}\">Start</button> ` + btnGroup;
  } else if (task.status === '已完成') {
    btnGroup = `<button class=\"revert-btn\" data-createdat=\"${task.createdAt}\">Revert</button> ` + btnGroup;
  }
  // 备注编辑按钮
  const descEditBtn = `<button class=\"edit-desc-btn\" data-createdat=\"${task.createdAt || ''}\" style=\"font-size:14px;padding:0 2px;margin-left:4px;background:none;border:none;cursor:pointer;vertical-align:middle;\" title=\"Edit\"><svg width='13' height='13' viewBox='0 0 24 24' fill='none' stroke='#1677ff' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M12 20h9' /><path d='M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4 12.5-12.5z'/></svg></button>`;
  li.innerHTML = `
    <div class=\"task-title\">
      <span>${task.title}</span>
      <span style=\"display:flex;align-items:center;gap:4px;\">
        ${durationStr}
        <span class=\"${statusClass}\" style=\"min-width:64px;text-align:right;\">${statusText}</span>
      </span>
    </div>
    <div class=\"task-desc\">
      <span class=\"desc-content\">${formatDescWithLinks(task.description)}</span>
      ${descEditBtn}
      ${task.createdAt ? `<br><span style='color:#aaa;font-size:12px;'>Started: ${formatDateTime(task.createdAt)}</span>` : ''}
      ${task.status === '已完成' && task.completedAt ? `<br><span style='color:#aaa;font-size:12px;'>Completed: ${formatDateTime(task.completedAt)}</span>` : ''}
      <div class='btn-group' style='justify-content:flex-end;gap:8px;margin-top:4px;'>
        ${btnGroup}
      </div>
    </div>
  `;
  document.getElementById('allTaskList').appendChild(li);
  // 备注编辑事件
  const editBtn = li.querySelector('.edit-desc-btn');
  if (editBtn) {
    editBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      const descSpan = li.querySelector('.desc-content');
      const oldDesc = task.description || '';
      // 替换为textarea和保存/取消按钮
      descSpan.outerHTML = `<textarea class='desc-edit-area' style='width:98%;min-height:60px;margin:4px 0;'>${oldDesc}</textarea>
                           <div style='font-size:11px;color:#888;margin-top:2px;'>Tip: Use [Display Text](URL) format to add links</div>`;
      editBtn.style.display = 'none';
      const descDiv = li.querySelector('.task-desc');
      const saveBtn = document.createElement('button');
      saveBtn.textContent = 'Save';
      saveBtn.style = 'font-size:12px;padding:0 8px;margin-left:4px;background:#1677ff;color:#fff;border-radius:4px;';
      const cancelBtn = document.createElement('button');
      cancelBtn.textContent = 'Cancel';
      cancelBtn.style = 'font-size:12px;padding:0 8px;margin-left:4px;background:#aaa;color:#fff;border-radius:4px;';
      descDiv.insertBefore(saveBtn, descDiv.querySelector('.btn-group'));
      descDiv.insertBefore(cancelBtn, descDiv.querySelector('.btn-group'));
      saveBtn.onclick = function(ev) {
        ev.stopPropagation();
        const newDesc = li.querySelector('.desc-edit-area').value;
        chrome.storage.local.get({tasks: []}, (result) => {
          const tasks = result.tasks;
          const realIdx = tasks.findIndex(t => t.createdAt === task.createdAt && t.title === task.title);
          if (realIdx !== -1) {
            tasks[realIdx].description = newDesc;
            chrome.storage.local.set({tasks}, () => {
              allTasksCache = tasks;
              renderAllTasks(allTasksCache, getFilterDateRange());
            });
          }
        });
      };
      cancelBtn.onclick = function(ev) {
        ev.stopPropagation();
        renderAllTasks(allTasksCache, getFilterDateRange());
      };
    });
  }
  // 事件绑定
  const startBtn = li.querySelector('.start-btn');
  if (startBtn) {
    startBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      const title = startBtn.getAttribute('data-title');
      chrome.storage.local.get({tasks: []}, (result) => {
        const tasks = result.tasks;
        const realIdx = tasks.findIndex(t => t.title === title && t.status === '待处理');
        if (realIdx !== -1) {
          tasks[realIdx].status = '进行中';
          tasks[realIdx].createdAt = new Date().toISOString();
          // 新增：初始化计时段
          tasks[realIdx].timerSegments = [{start: new Date().toISOString(), end: null}];
          tasks[realIdx].timerPaused = false;
          chrome.storage.local.set({tasks}, () => {
            allTasksCache = tasks;
            renderAllTasks(allTasksCache, getFilterDateRange());
          });
        }
      });
    });
  }
  const doneBtn = li.querySelector('.done-btn');
  if (doneBtn) {
    doneBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      const createdAt = doneBtn.getAttribute('data-createdat');
      chrome.storage.local.get({tasks: []}, (result) => {
        const tasks = result.tasks;
        const realIdx = tasks.findIndex(t => t.createdAt === createdAt && t.status === '进行中');
        if (realIdx !== -1) {
          const t = tasks[realIdx];
          // 结束前如未暂停，自动补end
          if (t.timerSegments && t.timerSegments.length > 0) {
            const lastSeg = t.timerSegments[t.timerSegments.length-1];
            if (lastSeg && !lastSeg.end) {
              lastSeg.end = new Date().toISOString();
            }
          }
          t.status = '已完成';
          t.completedAt = new Date().toISOString();
          t.timerPaused = false;
          chrome.storage.local.set({tasks}, () => {
            allTasksCache = tasks;
            renderAllTasks(allTasksCache, getFilterDateRange());
          });
        }
      });
    });
  }
  const deleteBtn = li.querySelector('.delete-btn');
  if (deleteBtn) {
    deleteBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      const createdAt = deleteBtn.getAttribute('data-createdat');
      const title = deleteBtn.getAttribute('data-title');
      chrome.storage.local.get({tasks: []}, (result) => {
        const tasks = result.tasks;
        let realIdx = -1;
        if (createdAt) {
          realIdx = tasks.findIndex(t => t.createdAt === createdAt && t.title === title);
        } else {
          realIdx = tasks.findIndex(t => t.title === title && t.status === '待处理');
        }
        if (realIdx !== -1) {
          tasks.splice(realIdx, 1);
          chrome.storage.local.set({tasks}, () => {
            allTasksCache = tasks;
            renderAllTasks(allTasksCache, getFilterDateRange());
          });
        }
      });
    });
  }
  const revertBtn = li.querySelector('.revert-btn');
  if (revertBtn) {
    revertBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      const createdAt = revertBtn.getAttribute('data-createdat');
      chrome.storage.local.get({tasks: []}, (result) => {
        const tasks = result.tasks;
        const realIdx = tasks.findIndex(t => t.createdAt === createdAt && t.status === '进行中');
        if (realIdx !== -1) {
          tasks[realIdx].status = '待处理';
          tasks[realIdx].createdAt = '';
          chrome.storage.local.set({tasks}, () => {
            allTasksCache = tasks;
            renderAllTasks(allTasksCache, getFilterDateRange());
          });
        } else {
          // 支持已完成回退
          const doneIdx = tasks.findIndex(t => t.createdAt === createdAt && t.status === '已完成');
          if (doneIdx !== -1) {
            tasks[doneIdx].status = '进行中';
            tasks[doneIdx].completedAt = '';
            // 回退后应为暂停状态
            tasks[doneIdx].timerPaused = true;
            chrome.storage.local.set({tasks}, () => {
              allTasksCache = tasks;
              renderAllTasks(allTasksCache, getFilterDateRange());
            });
          }
        }
      });
    });
  }
  // 开始/暂停按钮事件
  const playPauseBtn = li.querySelector('.play-pause-btn');
  if (playPauseBtn && task.status === '进行中') {
    playPauseBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      const createdAt = playPauseBtn.getAttribute('data-createdat');
      chrome.storage.local.get({tasks: []}, (result) => {
        const tasks = result.tasks;
        const realIdx = tasks.findIndex(t => t.createdAt === createdAt && t.status === '进行中');
        if (realIdx !== -1) {
          const t = tasks[realIdx];
          if (!t.timerSegments) t.timerSegments = [];
          if (t.timerPaused) {
            // 继续：push新段
            t.timerSegments.push({start: new Date().toISOString(), end: null});
            t.timerPaused = false;
          } else {
            // 暂停：当前段end赋值
            const lastSeg = t.timerSegments[t.timerSegments.length-1];
            if (lastSeg && !lastSeg.end) {
              lastSeg.end = new Date().toISOString();
            }
            t.timerPaused = true;
          }
          chrome.storage.local.set({tasks}, () => {
            allTasksCache = tasks;
            renderAllTasks(allTasksCache, getFilterDateRange());
          });
        }
      });
    });
  }
}

function getFilterDate() {
  return document.getElementById('doneDate').value;
}

document.addEventListener('DOMContentLoaded', function() {
  // 新增：默认只显示今天done的任务
  const today = new Date();
  const yyyy = today.getFullYear();
  const mm = String(today.getMonth() + 1).padStart(2, '0');
  const dd = String(today.getDate()).padStart(2, '0');
  const todayStr = `${yyyy}-${mm}-${dd}`;
  document.getElementById('doneDateStart').value = todayStr;
  document.getElementById('doneDateEnd').value = todayStr;
  document.getElementById('doneDateStart').addEventListener('change', function() {
    renderAllTasks(allTasksCache, getFilterDateRange());
  });
  document.getElementById('doneDateEnd').addEventListener('change', function() {
    renderAllTasks(allTasksCache, getFilterDateRange());
  });
  document.getElementById('clearFilterBtn').addEventListener('click', function() {
    document.getElementById('doneDateStart').value = '';
    document.getElementById('doneDateEnd').value = '';
    renderAllTasks(allTasksCache, {});
  });
  document.getElementById('backBtn').onclick = function() {
    window.close();
  };
  chrome.storage.local.get({tasks: []}, (result) => {
    allTasksCache = result.tasks;
    renderAllTasks(allTasksCache, getFilterDateRange());
  });
  // 导出按钮
  document.getElementById('exportBtn').onclick = function() {
    chrome.storage.local.get({tasks: []}, (result) => {
      const dataStr = JSON.stringify(result.tasks, null, 2);
      const blob = new Blob([dataStr], {type: 'application/json'});
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'tasks.json';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    });
  };
  // 导入按钮
  document.getElementById('importBtn').onclick = function() {
    document.getElementById('importFile').click();
  };
  document.getElementById('importFile').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = function(evt) {
      try {
        const imported = JSON.parse(evt.target.result);
        if (!Array.isArray(imported)) throw new Error('格式错误');
        chrome.storage.local.set({tasks: imported}, () => {
          allTasksCache = imported;
          renderAllTasks(allTasksCache, getFilterDateRange());
          alert('导入成功！');
        });
      } catch (err) {
        alert('导入失败，文件格式不正确！');
      }
    };
    reader.readAsText(file);
    e.target.value = '';
  });
  // 宽度切换功能
  const allTaskContainer = document.getElementById('allTaskContainer');
  const widthToggleBtn = document.getElementById('widthToggleBtn');
  const widthIcon = document.getElementById('widthIcon');
  const widths = [
    '900px', // 原始
    '1400px'  // 最宽
  ];
  let widthIdx = -1; // 默认不设置宽度
  function setAllWidth(idx) {
    if (idx === -1) {
      allTaskContainer.style.maxWidth = '';
      allTaskContainer.style.width = '';
    } else {
      allTaskContainer.style.maxWidth = widths[idx];
      allTaskContainer.style.width = '100%';
    }
  }
  setAllWidth(widthIdx);
  if (widthToggleBtn) {
    widthToggleBtn.onclick = function() {
      widthIdx = (widthIdx + 1) % widths.length;
      setAllWidth(widthIdx);
    };
  }
}); 